import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import {  useNavigate } from 'react-router-dom'
import {  message } from 'antd';
export default function Rldl() {
    let navigate = useNavigate()
    const [stream, setStream] = useState(null);
    const [photo, setPhoto] = useState(null);//图片base64
    const videoRef = useRef(null);
    const [messageApi, contextHolder] = message.useMessage();
    useEffect(() => {
        //打开摄像头并获取视频流
      navigator.mediaDevices.getUserMedia({ video: { 
        width: "320", 
        height:"240"
      } })
        .then(stream => {
          setStream(stream);
          videoRef.current.srcObject = stream;
        })
        .catch(error => console.log('Error accessing camera', error));
    }, []);


    useEffect(() => {
        return () => {
          if (stream) {
            stream.getTracks().forEach(track => {
              track.stop(); // 停止视频轨道
            });
          }
        };
      }, [stream]);
  
    const capturePhoto = () => {
      const canvas = document.createElement('canvas');
      canvas.width = videoRef.current.videoWidth;
      canvas.height = videoRef.current.videoHeight;
      canvas.getContext('2d').drawImage(videoRef.current, 0, 0);
      const dataURL = canvas.toDataURL('image/png');
      setPhoto(dataURL);
    }
    let dl=async ()=>{
        // console.log(photo.split(',')[1]);
        let {data}=await axios.post('http://localhost:3000/users/face',{
            img:photo.split(',')[1]
        })
        // console.log(data);
        if(data.code===200){
            //关闭摄像头
            // console.log(stream);
            // let videoTracks = stream.getVideoTracks();

            // 遍历所有视频轨道并调用stop方法
            // videoTracks.forEach(track => track.stop())


            sessionStorage.user=JSON.stringify(data.data)
            sessionStorage.userid=JSON.stringify(data.data._id)    
            sessionStorage.token=data.token                     
            navigate('/app/home')

          }else if (data.code===403) {
            messageApi.open({
                type: 'warning',
                content: data.msg,
              });
          }else{
            messageApi.open({
                type: 'error',
                content: data.msg,
              });
             
          }
    }
  return (
    <div>
        {contextHolder}
       {stream && <video  style={{width: '100%', height: 'auto'}} ref={videoRef} autoPlay />}
      {stream && <button  onClick={capturePhoto}>拍摄照片</button>}
      {photo && <img style={{width: '100%', height: 'auto'}} src={photo} alt="Captured photo" />}
      {photo &&  <button  onClick={dl}>人脸登录</button>}
    </div>
  )
}
